#!/usr/bin/env python3
# - owner
# - repo
# - pr_num
# - comment
import json
import os
import sys
sys.path.append(
    os.path.join(os.getenv("LKP_SRC"), "programs/gitee-comment-pr"))
import re
from bs4 import BeautifulSoup

from utils.gitee_proxy import GiteeProxy


lkp_src = os.getenv('LKP_SRC')
owner = os.getenv('owner')
repo = os.getenv('repo')
pr_num = os.getenv('pr_num')
comment = os.getenv('comment')
token = os.getenv('secrets_token')

emoji_map = {
    "SUCCESS": ":white_check_mark:",
    "WARNING": ":bug:",
    "FAILED": ":x:",
    "EXCLUDE": ":ballot_box_with_check:"
    }

package_status = {
    # build status
    201: "SUCCESS",     # BUILD_SUCCESS
    202: "FAILED",      # BUILD_FAILED
    203: "FAILED",      # BUILD_ABORTED
    205: "EXCLUDED",    # BUILD_EXCLUDED
    # package status
    103: "SUCCESS",     # JOB_SUCCESS
    104: "FAILED",      # JOB_FAILED
    105: "FAILED",      # JOB_UNRESOLVABLE
    106: "EXCLUDED",    # JOB_EXCLUDED
    107: "FAILED",      # JOB_ABORTED
    108: "FAILED",      # JOB_UNKNOWN
    109: "SUCCESS",     # JOB_CYCLE_SUCCESS
    110: "FAILED",      # JOB_CYCLE_FAILED
    112: "FAILED"       # JOB_OOM
    }

soup = BeautifulSoup(comment, features="lxml")
table = soup.find('table')

for key, value in package_status.items():
    tds = soup.find_all('td', text=re.compile(str(key)))
    for td in tds:
        td.string.replace_with(value)

for key, value in emoji_map.items():
    tds = soup.find_all('td', text=re.compile(key))
    for td in tds:
        td.string.replace_with(f"{value}{key}")

comment = soup.prettify()
print(comment)
gp = GiteeProxy(owner, repo, token)
commented = gp.comment_pr(pr_num, comment)

if not commented:
    raise RuntimeError(
        f"Comment to https://gitee.com/{owner}/{repo}/pulls/{pr_num} failed."
    )
